package org.artifact.core.plugin.netty;

import cn.hutool.core.map.MapUtil;
import org.artifact.core.lang.AbstractPlugin;
import org.artifact.core.plugin.netty.server.NettyServer;
import org.artifact.core.plugin.netty.server.NettySocketServer;
import org.artifact.core.plugin.netty.server.NettyWebSocketServer;
import org.artifact.core.server.ServerConfig;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author : SandKing
 * @CreateDate : 2020/3/25 15:31
 * @Description ：Please describe this document
 */
public class NettyPlugin extends AbstractPlugin {
    /*
    网络模型
     */
    static final String TPC = "tcp";
    static final String WEB_SOCKET = "websocket";
    static final String HTTP = "http";
    static final String KCP = "kcp";
    static final String UDP = "udp";

    private Map<String,NettyServer> servers = new LinkedHashMap<>();


    @Override
    public boolean start() {
        Map<String,Map> nettys = ServerConfig.me().deepGet("plugins.netty");
        
        for (Entry<String, Map> e : nettys.entrySet()) {
        	if ("default".equals(e.getKey())) {
				continue;
			}
        	NettyServer nettyServer = createNettyServer(e.getValue());
            nettyServer.init(e.getValue());
            servers.put(e.getKey(),nettyServer);
		}

        for (NettyServer server : servers.values()) {
            server.startup();
        }
        return true;
    }

    private NettyServer createNettyServer(Map netty) {
        String model = MapUtil.getStr(netty, "model");
        switch (model){
            case TPC:
                return new NettySocketServer();
            case WEB_SOCKET:
                return new NettyWebSocketServer();
            case HTTP:
                return null;
            case KCP:
                return null;
            case UDP:
                return new NettySocketServer();
            default:
                return null;
        }
    }

    @Override
    public boolean stop() {
        for (NettyServer server : servers.values()) {
            server.shutdown();
        }
        return true;
    }
}
